package com.cevent.community.app.business.controller.member;/**
 * Created by Cevent on 2021/9/16.
 */

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author cevent
 * @description 验证码接口
 * @date 2021/9/16 14:43
 */
@RestController
@RequestMapping("/member/captcha")
public class CaptchaController {
    public static final String BUSINESS_NAME="图形验证码";
    public static final Logger LOG= LoggerFactory.getLogger(CaptchaController.class);
    //@Qualifier：限定@Autowired自动注入的@bean
    @Qualifier("getDefaultKaptcha")
    @Autowired
    DefaultKaptcha defaultKaptcha;

    //注入redis
    @Resource
    RedisTemplate redisTemplate;

    @GetMapping("/code/{imgCodeToken}")
    public void getCaptcha(@PathVariable(value="imgCodeToken") String imgCodeToken,
                           HttpServletRequest request, HttpServletResponse response) throws IOException{
        //客户端传入sessionId: JSESSIONID=74C5595606A8BF279AE9B4D56839C16A; Path=/business; HttpOnly
        LOG.info("客户端传入的sessionID=JSESSIONID：{}",request.getSession().getId());
        //LOG.info("客户端传入的cookieID：{}",request.getCookies().toString());
        //指定字节数组输出流
        ByteArrayOutputStream jpegOutputStream=new ByteArrayOutputStream();
        try {
            //1.自动生成验证码字符串
            String createCode=defaultKaptcha.createText();
            //2.将生成的验证码放入会话缓存(绑定imgCodeToken和createCode)，后需验证码的时候方便调用
            request.getSession().setAttribute(imgCodeToken,createCode);
            //TODO 注入redis(key：传入的8位uuid，value：生成的kaptcha文本，过期时间：3000，时间单位：TimeUnit)
            //超过过期时间，redis将清空存入的数据,300s，5分钟后清空数据，存储为key
            redisTemplate.opsForValue().set(imgCodeToken,createCode,300, TimeUnit.SECONDS);
            //获取redis中的imgCodeToken
            String redisCode=(String)redisTemplate.opsForValue().get(imgCodeToken);
            LOG.info("redis中存储的imgCodeToken，5分钟清除：{}",redisCode);
            //3.将验证码字符串放入jpeg
            BufferedImage challengeCaptcha=defaultKaptcha.createImage(createCode);
            ImageIO.write(challengeCaptcha,"jpg",jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            e.printStackTrace();
            return;
        }
        //定义response输出类型为image/jpeg(需要转换字节数组)，使用response输出流，输出图片的byte数组
        byte[] jpgChallengeCaptcha=jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        //设置过期时间
        response.setDateHeader("Expires",0);
        //设置图片格式，注意，图片jpg格式，对应的contentType=image/jpeg
        response.setContentType("image/jpeg");
        //配置response中的输出流
        ServletOutputStream outputStream=response.getOutputStream();
        //输出流写入内容
        outputStream.write(jpgChallengeCaptcha);
        LOG.info("验证码输出成功：{}",outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
